package cn.edu.zafu.bigdata.x.Foo;

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;

public class TimeServer {
    public static void main(String[] args) throws IOException {
        int port = 3000; // 服务端端口
        DatagramSocket serverSocket = new DatagramSocket(port);
        System.out.println("Time server is running and waiting for client requests...");

        while (true) {
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);

            // 获取当前服务端的时间戳
            long serverTime = System.currentTimeMillis();

            // 将服务端的时间戳发送给客户端
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();
            ByteBuffer.wrap(sendData).putLong(serverTime);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
            serverSocket.send(sendPacket);
        }
    }
}